package com.note.es.service.impl;


import com.note.es.service.IndexService;
import com.note.es.entity.IndexEntity;
import com.note.es.utils.IndexUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class IndexServiceImpl implements IndexService {

    private IndexUtil indexUtil;

    @Override
    public boolean createIndex(String indexType, String indexName) throws IOException {
        boolean isSuccess = false;
        IndexEntity indexEntity = new IndexEntity();
        indexEntity.setName(indexName);
        if ("news".equals(indexType)) {
            indexEntity.setType("article");
            InputStream inputStream = this.getClass()
                    .getClassLoader().getResourceAsStream("es_mappings/warning_news_mapping.json");
            indexEntity.setMappings(inputStreamAsString(inputStream));
            isSuccess = indexUtil.createIndex(indexEntity);
        } else if ("social".equals(indexType)) {
            indexEntity.setType("social");
            InputStream inputStream = this.getClass()
                    .getClassLoader().getResourceAsStream("es_mappings/warning_social_mapping.json");
            indexEntity.setMappings(inputStreamAsString(inputStream));
            isSuccess = indexUtil.createIndex(indexEntity);
        } else if ("hot".equals(indexType)) {
            indexEntity.setType("hot");
            InputStream inputStream = this.getClass()
                    .getClassLoader().getResourceAsStream("es_mappings/hot_mapping .json");
            indexEntity.setMappings(inputStreamAsString(inputStream));
            isSuccess = indexUtil.createIndex(indexEntity);
        }
        return isSuccess;
    }


    @Override
    public boolean deleteIndex(String indexName) throws IOException {
        return indexUtil.deleteIndex(indexName);
    }


    /**
     * 输入流转字符串
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    private String inputStreamAsString(InputStream inputStream) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "UTF-8");
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0){
                break;
            }
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
}
